package com.itbac.mongodemo.mongo;

import cn.hutool.core.lang.Snowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class MongoInsertEventListener extends AbstractMongoEventListener<MongoEntity> {

    @Autowired
    private Snowflake snowflake;

    private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public void onBeforeConvert(BeforeConvertEvent<MongoEntity> event) {
        MongoEntity entity = event.getSource();
        // 判断 id 为空
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(timeFormatter);
        String date = now.format(dateFormatter);
        if (entity.getId() == 0) {
            // 雪花算法
            long id = 5L;
            // 设置主键
            entity.setId(id);
            //创建日期，时间
            entity.setCreateDate(date);
            entity.setCreateTime(time);
            //更新日期，时间
            entity.setUpdateDate(date);
            entity.setUpdateTime(time);
        }
        //不支持更新事件
    }


}
